package com.webchat.chat.web.chat;

import com.webchat.chat.core.baseEntity.Result;
import com.webchat.chat.core.baseEntity.ResultGenerator;
import com.webchat.chat.core.enums.SocketRoomStatus;
import com.webchat.chat.core.redis.RedisService;
import com.webchat.chat.core.tools.ChatConstant;
import com.webchat.chat.core.tools.RedisConstant;
import com.webchat.chat.core.tools.ShiroUtil;
import com.webchat.chat.model.RoomClient;
import com.webchat.chat.model.SocketClient;
import com.webchat.chat.service.RoomClientService;
import com.webchat.chat.service.UserService;
import com.webchat.chat.web.BaseController;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * Created by Owner on 2018/6/29.
 */
@RestController
@RequestMapping(ChatConstant.CONTROLLER_ROOT_PATH + "/chat/cs")
public class CustomerServiceController extends BaseController {
    @Resource
    private UserService userService;
    @Resource
    private RoomClientService roomClientService;

    @Resource
    private RedisService redisService;

    @PostMapping("/list")
    public Result list(String roomId) {
        if(StringUtils.isBlank(roomId)){
            return ResultGenerator.genFailResult("roomId不能为空");
        }
        String tenantCode = ShiroUtil.getTenantCode();
        if(StringUtils.isBlank(tenantCode)){
            return ResultGenerator.genFailResult("租户代号必填！");
        }

        List<RoomClient> roomClients = roomClientService.findByRoomId(roomId, SocketRoomStatus.正常);

        List<SocketClient> availableCS = userService.getAvailableCS(tenantCode);
        if(roomClients == null && roomClients.isEmpty()){
            return ResultGenerator.genSuccessResult(availableCS);
        }
        Set<String> clientIds = roomClients.stream().map(RoomClient::getClientId).distinct().collect(Collectors.toSet());
        List<SocketClient> rs = availableCS.stream().filter(cs -> !clientIds.contains(cs.getUserId())).collect(Collectors.toList());

        return ResultGenerator.genSuccessResult(rs);

    }

    @PostMapping("/online-list")
    public Result onlineList() {
        String tenantCode = ShiroUtil.getTenantCode();
        Collection<SocketClient> rs = null;
        Map<String, SocketClient> onlineMap = redisService.getMap(RedisConstant.SCOKET_CLIENT_CS + tenantCode);
        if(onlineMap != null){
            rs = onlineMap.values();
        }
        return ResultGenerator.genSuccessResult(rs);
    }
}
